#
# 手机微信上截图，图片是相同的大小，在发布之前，要把顶部的客户手机号打马赛克，
# 要把左侧客户头像打马赛克
#
# 这个脚本就是用来批理给手机微信聊天截图打马赛克的，2个区域，顶部手机号，左侧头像
#
#


import cv2
import numpy as np
import os

face_location = [500, 200, 900, 320]  # x1,y1,x2,y2  x1,y1为人脸左上角点；x2,y2为人脸右下角点

mobile_location = [552, 173, 901, 251]  # x1,y1,x2,y2  x1,y1为马赛克区域左上角点；x2,y2为马赛克区域右下角点
avatar_location = [0, 281, 172, 2255]


def try_file_path(file_path):
    """测试是否存在文件，如果存在，返回带括号的文件名"""
    tmp_path = file_path
    (root, ext) = os.path.splitext(file_path)
    i = 1
    while os.path.exists(tmp_path):
        tmp_path = f"{root}({i}){ext}"
        i += 1

    return tmp_path


# 正规马赛克
def do_mosaic(img, x, y, w, h, neighbor=9):
    """
    :param rgb_img
    :param int x :  马赛克左顶点
    :param int y:  马赛克左顶点
    :param int w:  马赛克宽
    :param int h:  马赛克高
    :param int neighbor:  马赛克每一块的宽
    """
    for i in range(0, h, neighbor):
        for j in range(0, w, neighbor):
            rect = [j + x, i + y]
            color = img[i + y][j + x].tolist()  # 关键点1 tolist
            left_up = (rect[0], rect[1])
            x2 = rect[0] + neighbor - 1  # 关键点2 减去一个像素
            y2 = rect[1] + neighbor - 1
            if x2 > x + w:
                x2 = x + w
            if y2 > y + h:
                y2 = y + h
            right_down = (x2, y2)
            cv2.rectangle(img, left_up, right_down, color, -1)  # 替换为为一个颜值值

    return img


def fill_location(location):
    """从区域左上角、右下角的坐标，计算宽高"""
    x = location[0]
    y = location[1]
    w = location[2] - location[0]
    h = location[3] - location[1]

    return (x, y, w, h)


def mosaic_file(file_path):
    print("打码", file_path)

    img = cv2.imread(file_path)  # opencv读取的是BGR数组
    area1 = fill_location(mobile_location)
    area2 = fill_location(avatar_location)

    img_mosaic = do_mosaic(img, area1[0], area1[1], area1[2], area1[3], neighbor=15)
    img_mosaic = do_mosaic(
        img_mosaic, area2[0], area2[1], area2[2], area2[3], neighbor=55
    )

    target = try_file_path(os.path.basename(file_path))
    cv2.imwrite(target, img_mosaic)


def isPic(val):
    ext = os.path.splitext(val)[1]
    print(ext)


def main():
    files = [os.path.join("src", f) for f in os.listdir("src")]
    for f in files:
        isPic(f)
        mosaic_file(f)


if __name__ == "__main__":
    main()
